<script setup>
import {useRouter} from "vue-router";
import {onBeforeMount, onMounted, onUnmounted, proxyRefs, reactive, ref} from "vue";
import {baseUrl} from "@/utils/request.js";
import {useUserIdStore} from "@/stores/userInfo.js";
import {Message, User} from "@element-plus/icons-vue";
import ContactsItem from "@/components/ContactsItem.vue";
import UserMessageItem from "@/components/UserMessageItem.vue";
import {createContactService, deleteContactService, getContactsService} from "@/api/contacts.js";
import {getChatMessagesService, getTotalNoticeNumService, setIsReadService} from "@/api/messages.js";
import {getUserInfoService} from "@/api/user.js";
import Head from "@/components/Head.vue";

const userIdStore = useUserIdStore();
const route = useRouter();
const title = ref('');
const userId = ref(userIdStore.userId); // 当前用户id

const contacts = ref([]); // 联系人列表
const contactsClicked = ref([]); // 当前点击的联系人列表
const contactUser = ref(null); //从外部点击的联系人id，通过路由传递过来的
const itemIndex = ref(null); //当前点击的联系人列表的索引
const messages = ref([]); // 消息列表
const sendUserPic = ref(null); // 当前用户头像
const inputMsg = ref('')

const msgContent = ref(null);

let websocketInstance;
// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
const url = ref(
    baseUrl.replace('http:', 'ws:').replace('https:', 'wss:') + '/websocket/' + userId.value
)
onMounted( () => {
  title.value = route.currentRoute.value.meta.title;
  document.title = title.value;

  // 初始化websocket
  websocketInstance = initWebSocket();

  // 滚动条滚动到最底部
  scrollToBottom();
})

const getUserInfo = async ()=>{
  let res = await getUserInfoService(userId.value);
  sendUserPic.value = res.data.userPic;
}
getUserInfo();



//获取联系人
const getContacts = async ()=>{
  contactUser.value = route.currentRoute.value.query.contactUserId;
  if (contactUser.value!==null && contactUser.value!==''&& contactUser.value!==undefined){
    await createContactService(contactUser.value);
    let result = await getContactsService();
    contacts.value = result.data;
    defaultClickedValue();
    for (let i = 0; i < contacts.value.length; i++){
      if (contacts.value[i].contactUserId.toString() === contactUser.value){
        contactsClicked.value[i].isClicked = true;
        itemIndex.value = i;
        break;
      }
    }
    let msgRes = await getChatMessagesService(contactUser.value);
    messages.value = msgRes.data;
  }else{
    let result =await getContactsService();
    contacts.value = result.data;
    defaultClickedValue();
  }
}
getContacts();

const itemClicked =async (index) =>{
  await setIsReadService(contactsClicked.value[index].contactUserId);
  let result =await getContactsService();
  contacts.value = result.data;
  defaultClickedValue();
  contactsClicked.value[index].isClicked = true;
  itemIndex.value = index;
  //获取消息列表
  let msgResult = await getChatMessagesService(contactsClicked.value[index].contactUserId);
  messages.value = msgResult.data;
  setTimeout(()=>{
    // 滚动条滚动到最底部
    scrollToBottom();
  },0.01)
}

// 点击联系人恢复默认值
const defaultClickedValue = ()=>{
  contactsClicked.value = [];
  if (contacts.value.length>0){
    for (let i = 0; i < contacts.value.length; i++){
      const param = {
        contactUserId: contacts.value[i].contactUserId,
        isClicked: false
      }
      contactsClicked.value.push(param);
    }
  }
}

// 初始化websocket
const initWebSocket = () => {
  const websock = new WebSocket(url.value);
  websock.onopen = websocketonopen;
  websock.onerror = websocketonerror;
  websock.onmessage = websocketonmessage;
  websock.onclose = websocketclose;
  return websock;
}

const sendMsg = async () => {
  if (inputMsg.value === ''){
    return;
  }
  const inputData = "{"+"\"sendUser\":"+userId.value+","+"\"receiveUser\":"+contactsClicked.value[itemIndex.value].contactUserId+","+"\"messageContent\":\""+inputMsg.value+"\"}";
  const receiverId = contactsClicked.value[itemIndex.value].contactUserId;
  websocketInstance.send(inputData)
  inputMsg.value = '';
  console.log("发送消息")
  await reGetInfo();
  defaultClickedValue();
  contactsClicked.value.forEach((item,index)=>{
    if (item.contactUserId === receiverId){
      item.isClicked = true;
      itemIndex.value = index;
    }
  })
  // 滚动条滚动到最底部
  scrollToBottom();
}


// 连接成功后调用
const websocketonopen = () => {
  console.log("WebSocket连接成功");
}
// 发生错误时调用
const websocketonerror = (e) => {
  console.log("WebSocket连接发生错误");
}
// 接收后端消息
// vue 客户端根据返回的cmd类型处理不同的业务响应
const websocketonmessage = async (e) => {
  // const data = eval("(" + e.data + ")");
  // //处理订阅信息
  // if(data.cmd == "topic"){
  //   //TODO 系统通知
  //
  // }else if(data.cmd == "user"){
  //   //TODO 用户消息
  //
  // }
  const msg = e.data
  console.log("收到消息：" + msg)
  await reGetInfo();
}
// 关闭连接时调用
const websocketclose = (e) => {
  console.log("connection closed (" + e.code + ")");
}

// 重新加载视图
const reGetInfo = async ()=>{
  let result =await getContactsService();
  contacts.value = result.data;

  //获取消息列表
  let msgResult = await getChatMessagesService(contactsClicked.value[itemIndex.value].contactUserId);
  messages.value = msgResult.data;
}

const deleteContacts = async ()=>{
  await deleteContactService(contactsClicked.value[itemIndex.value].contactUserId);
  let result =await getContactsService();
  contacts.value = result.data;
  await defaultClickedValue();
  if (contactsClicked.value.length !== 0){
    itemIndex.value = (itemIndex.value+1)%contactsClicked.value.length;
    let msgResult = await getChatMessagesService(contactsClicked.value[itemIndex.value].contactUserId);
    messages.value = msgResult.data;
  }else {
    itemIndex.value = null;
    messages.value = [];
  }
}

const setRead = async ()=>{
  if (itemIndex!==null){
    await setIsReadService(contactsClicked.value[itemIndex.value].contactUserId);
    await reGetInfo();
    scrollToBottom();
  }
}

const scrollToBottom = ()=>{
  if (msgContent.value) {
    msgContent.value.scrollTop = msgContent.value.scrollHeight;
  }
}

const keydown = (e)=>{
  if (e.keyCode === 13 && !e.ctrlKey){
    e.preventDefault();
    sendMsg();
  }
  if (e.ctrlKey && e.keyCode === 13){
    e.preventDefault();
    inputMsg.value += '\n';
  }
}
window.addEventListener('keydown', keydown);
onUnmounted(()=>{
  window.removeEventListener('keydown', keydown);
})
</script>

<template>
  <div class="container">
    <Head :title="title" :index="0"/>
    <div class="body">
      <div class="msg-container">
        <div class="left">
          <div v-if="contacts!==null && contacts.length !== 0" class="contact-list">
            <ContactsItem
                v-for="(item, index) in contacts"
                :key="index"
                :contactUsername="item.contactUserName"
                :userPic="item.userPic"
                :newContent="item.newContent"
                :new-msg-time="item.newMsgTime"
                :noticeNum="item.noticeNum"
                @click="itemClicked(index)"
                :style="contactsClicked[index].isClicked ? 'background-color: #e5e5e5':''"/>
          </div>
          <el-empty v-else style="" description="暂无联系人"/>
        </div>
        <div v-if="itemIndex!=null" class="right">
          <div class="right-title">
            <div style="display: flex;">
              <p>{{ contacts[itemIndex].contactUserName }}</p>
              <p v-if="contacts[itemIndex].online" class="user-status" style="color: #00e052">(在线)</p>
              <p v-else class="user-status" style="color: rgb(171,171,171);">(离线)</p>
            </div>
            <el-dropdown class="drop-down" trigger="click">
              <span class="el-dropdown-link">
                ···
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="deleteContacts()">删除当前对话</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          <div class="right-middle" @click="setRead">
            <div v-if="messages!==null && messages.length !== 0" ref="msgContent" class="msg-content">
              <UserMessageItem
                  v-for="(item, index) in messages"
                  :key="index"
                  :is-read="item.isRead"
                  :message-content="item.messageContent"
                  :time="item.createTime"
                  :is-self="item.self"
                  :send-user-pic="sendUserPic"
                  :receive-user-pic="contacts[itemIndex].userPic"/>
            </div>
            <el-empty v-else style="" description="暂无内容..."/>
          </div>
          <div class="right-bottom" @click="setRead">
            <textarea v-model="inputMsg" class="msg-input" placeholder="在这里发送消息..."></textarea>
            <button @click="sendMsg">发送(Enter)</button>
          </div>
        </div>
        <!-- 未选择联系人之前全部展示空 -->
        <div v-else class="right">
          <div class="right-title">
          </div>
          <div class="right-middle">
          </div>
          <div class="right-bottom">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  height: 100vh;
  width: 100vw;
  .body {
    width: 100%;
    height: 91%;
    background-color: #eeeeee;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .msg-container {
    width: 80%;
    height: 90%;
    border-radius: 10px;
    background-color: white;
    display: flex;
  }

  .left {
    width: 25%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e0e0e0;

    .contact-list {
      width: 100%;
      height: 100%;
      overflow: auto;
    }
  }

  .right {
    width: 75%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .right-title {
      width: 100%;
      height: 10%;
      border-bottom: 1px solid #e0e0e0;
      display: flex;
      justify-content: space-between;
      align-items: center;

      p {
        margin: 0 18px;
        font-size: 20px;
      }
      .user-status{
        margin-left: -10px;
        font-size: 14px;
        margin-top: 8px;
        user-select: none;
      }

      .drop-down{
        margin-right: 24px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        user-select: none;
        &:hover{
          color: #b7b7b7;
        }
      }
    }

    .right-middle {
      width: 100%;
      height: 70%;
      display: flex;
      justify-content: center;
      align-items: center;
      border-bottom: 1px solid #e0e0e0;
      .msg-content{
        width: 100%;
        height: 100%;
        overflow-y: auto;
        overflow-x: hidden;
        padding: 0 18px;
      }
    }

    .right-bottom {
      width: 100%;
      height: 20%;
      position: relative;

      .msg-input {
        width: 97%;
        padding: 10px;
        resize: none;
        border: none;
        height: 35%;
        font-size: 16px;

        &:focus {
          outline: none;
          box-shadow: none;
        }
      }

      button {
        position: absolute;
        width: 10%;
        height: 30%;
        right: 30px;
        bottom: 20px;
        border: none;
        border-radius: 6px;
        color: #49CD88;
        background-color: #E9E9E9;
        font-size: 15px;

        &:hover {
          background-color: #d7d6d6;
          cursor: pointer;
        }
      }
    }
  }
}
</style>